package com.gitee.cui.concurrency.concurrent;

import com.gitee.cui.util.Print;

import java.util.concurrent.Callable;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.FutureTask;

/**
 * 通过Future方式实现泡茶逻辑
 *
 * @author cuiqingqiang
 * @version 1.0
 * @date 2021/12/9 15:40
 **/
public class JavaFutureDemo {

    private static final int SLEEP_GAP = 500;

    public static String getCurrentThreadName() {
        return Thread.currentThread().getName();
    }

    static class HotWaterJob implements Callable<Boolean> {

        @Override
        public Boolean call() throws Exception {
            try {
                Print.tcfo("洗好水壶");
                Print.tcfo("灌上凉水");
                Print.tcfo("放在火上");
                Thread.sleep(SLEEP_GAP);
                Print.tcfo("水开了");
            } catch (InterruptedException e) {
                Print.tcfo("烧水任务 发生异常被中断");
                return false;
            }
            Print.tcfo("烧水任务 运行结束");
            return true;
        }
    }

    static class WashJob implements Callable<Boolean> {

        @Override
        public Boolean call() throws Exception {
            try {
                Print.tcfo("洗茶壶");
                Print.tcfo("洗茶杯");
                Print.tcfo("拿茶叶");
                Thread.sleep(SLEEP_GAP);
                Print.tcfo("洗完了");
            } catch (InterruptedException e) {
                Print.tcfo("清洗任务 发生异常被中断");
                return false;
            }
            Print.tcfo("清洗任务 运行结束");
            return true;
        }
    }

    public static void drinkTea(boolean hotWater, boolean wash) {
        if (hotWater && wash) {
            Print.tcfo("泡茶喝");
        } else if (!hotWater) {
            Print.tcfo("烧水失败，没有茶喝了");
        } else if (!wash) {
            Print.tcfo("清洗失败，没有茶喝了");
        }
    }

    public static void main(String[] args) {
        Thread.currentThread().setName("主线程");
        HotWaterJob hotWaterJob = new HotWaterJob();
        WashJob washJob = new WashJob();
        FutureTask<Boolean> hTask = new FutureTask<>(hotWaterJob);
        FutureTask<Boolean> wTask = new FutureTask<>(washJob);

        Thread hThread = new Thread(hTask, "** 烧水-Thread");
        Thread wThread = new Thread(wTask, "$$ 清洗-Thread");
        hThread.start();
        wThread.start();

        try {
            Boolean hotWater = hTask.get();
            Boolean wash = wTask.get();
            drinkTea(hotWater, wash);
        } catch (InterruptedException e) {
            Print.tcfo(getCurrentThreadName() + "发生异常被中断");
        } catch (ExecutionException e) {
            e.printStackTrace();
        }
        Print.tcfo(getCurrentThreadName() + "运行结束");
    }
}
